import Cookies from 'js-cookie';
import userStore from '@/store/userStore';
import configStore from '@/store/configStore';
import { getStringItem } from '@/utils/storage';
import { StorageEnum } from '@/types/enum';

const { VITE_LOGOUT_PAGE: LOGOUTPAGE } = import.meta.env;
const { VITE_AUTH_FLAG: AUTHFLAG } = import.meta.env;
const { VITE_TOKEN: VITETOKEN } = import.meta.env;
const authFlag = AUTHFLAG === 'true' ? true : false;

export const logout = (router?: any): void => {
  configStore.getState().actions.clearConfig();
  // userStore.getState().actions.clearUserInfoAndToken();
  window.location.href = LOGOUTPAGE
  // try {
  //   const hostname = new URL(window.location.origin).hostname;
  //   Cookies.set(VITETOKEN, '', { path: '/', domain: hostname, expires: new Date(0) });
  //   Cookies.set('access_token', '', { path: '/', domain: hostname, expires: new Date(0) });
  //   Cookies.remove(VITETOKEN);
  //   Cookies.remove('access_token');
  //   const loginPageDisplay = getStringItem(StorageEnum.LoginPageDisplay)
  //   const protocolName = getStringItem(StorageEnum.protocolName)
  //   const isRuiLogin = loginPageDisplay?.toLowerCase() === 'true'
  //   configStore.getState().actions.clearConfig();

  //   let page = LOGOUTPAGE
  //   if (protocolName || protocolName != null) {
  //     page = page + '?protocolName=' + protocolName
  //   }

  //   // window.location.href = LOGOUTPAGE;
  //   if ((authFlag || !isRuiLogin) && LOGOUTPAGE) {
  //     // userStore.getState().actions.clearUserInfo();
  //     window.location.href = page;
  //   } else {
  //     userStore.getState().actions.clearUserInfoAndToken();
  //     router && router.push('/login');
  //   }
  // } catch (error) {
  //   console.log(error);
  // }
};

export const resetCookie = (): void => {
  try {
    const hostname = new URL(window.location.origin).hostname;
    Cookies.set(VITETOKEN, '', { path: '/', domain: hostname, expires: new Date(0) });
    Cookies.set('access_token', '', { path: '/', domain: hostname, expires: new Date(0) });
    Cookies.remove(VITETOKEN);
    Cookies.remove('access_token');
    configStore.getState().actions.clearConfig();
  } catch (error) {
    console.log(error);
  }
};
